package com.swu.cx.kotlinmodule.dex_encode

import java.io.File
import java.io.FileOutputStream


fun main() {
    // 1.清理目录
    clearTempFile()
    // 2.解压apk文件
    val newApkFile = unZipAPk()
    // 3.处理aar 获得壳dex
    createShellDexFile(newApkFile)
    // 4.打包签名
    signApk(newApkFile)
}

private fun clearTempFile() {
    val file = File("KotlinModule/src/main/java/com/swu/cx/kotlinmodule/dex_encode/aar/temp")
    if(file.exists()) {
        file.listFiles()?.forEach {
            if (file.isFile) file.delete()
        }
    }

    val file2 = File("KotlinModule/src/main/java/com/swu/cx/kotlinmodule/dex_encode/apk/temp")
    if(file2.exists()) {
        file2.listFiles()?.forEach {
            if (file.isFile) file.delete()
        }
    }
}

private fun unZipAPk(): File {
    AES.init(AES.DEFAULT_PWD)
    val apkFile = File("KotlinModule/src/main/java/com/swu/cx/kotlinmodule/dex_encode/apk/app-debug.apk")
    val newApkFile = File(apkFile.parent + File.separator + "temp").apply { ensureFileExits() }
    val mainDexFile = AES.encryptAPKFile(apkFile, newApkFile)
    if (newApkFile.isDirectory) {
        newApkFile.listFiles()?.forEach { file ->
            if (file.isFile && file.name.endsWith(".dex")) {
                println("rename step 1:" + file.name)
                val newName = file.parent + File.separator + file.name.substring(
                    0, file.name.indexOf(
                        ".dex"
                    )
                ) + "_.dex"
                println("rename step 2" + newName)
                file.renameTo(File(newName))
            }
        }
    }
    return newApkFile
}

private fun createShellDexFile(newApkFile: File) {
    val file = File("KotlinModule/src/main/java/com/swu/cx/kotlinmodule/dex_encode/aar/encode_library-debug.aar")
    val aarDex = Dx.jar2Dex(file)

    val tempMainDex = File(newApkFile.path + File.separator + "classes.dex").apply { ensureFileExits() }
    //        System.out.println("MyMain" + tempMainDex.getAbsolutePath());
    val fos = FileOutputStream(tempMainDex)
    val fbytes = Utils.getBytes(aarDex)
    fos.write(fbytes)
    fos.flush()
    fos.close()
}

private fun signApk(newApkFile: File) {
    val unSignedApk = File("KotlinModule/src/main/java/com/swu/cx/kotlinmodule/dex_encode/res/apk-unsigned.apk")
    Zip.zip(newApkFile, unSignedApk)

    val signedApk = File("KotlinModule/src/main/java/com/swu/cx/kotlinmodule/dex_encode/res/apk-signed.apk")
    Signature.signature(unSignedApk, signedApk)
}

private fun File.ensureFileExits() {
    if (!this.exists()) {
        createNewFile()
    }
}